package com.wh.springboot.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.log.Log;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wh.springboot.common.Constants;
import com.wh.springboot.common.entity.Menu;
import com.wh.springboot.common.entity.User;
import com.wh.springboot.common.entity.dto.UserDTO;
import com.wh.springboot.exception.ServiceException;
import com.wh.springboot.mapper.RoleMapper;
import com.wh.springboot.mapper.RoleMenuMapper;
import com.wh.springboot.mapper.UserMapper;
import com.wh.springboot.service.IMenuService;
import com.wh.springboot.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wh.springboot.utils.TokenUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author elsy
 * @since 2023-01-09
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    private static final Log LOG = Log.get();
    @Resource
    private RoleMapper roleMapper;

    @Resource
    private RoleMenuMapper roleMenuMapper;

    @Resource
    private IMenuService menuService;

    @Resource
    private UserMapper userMapper;

    @Override
    public UserDTO login(UserDTO userDTO) {
        User one = getUserInfo(userDTO);
        if (one != null) {//从数据库查得到信息
            BeanUtil.copyProperties(one, userDTO, true);//copy 数据库查询到的one数据 copy到我们的userDTO中
            //设置token
            String token = TokenUtils.getToken(one.getId().toString(), one.getPassword());
            userDTO.setToken(token);

            String role = one.getRole();//获取用户角色 ROLE_ADMIN
            //设置用户的菜单列表
            List<Menu> roleMenus = getRoleMenus(role);
            userDTO.setMenus(roleMenus);
            return userDTO;
        } else {//错误，得不到数据,其他业务异常
            throw new ServiceException(Constants.Status_600, "用户名或者密码错误");
        }


        //  查找一个数据
        //  User one=getOne(queryWrapper);
        //   return one != null;


        //查询多条数据，
        // 方法一：不返回一个，查出多个
        //        List<User> list = list(queryWrapper);
        //只要有一个就让它过
        //        return list.size() != 0;


    }

    //注册
    @Override
    public User register(UserDTO userDTO) {
        User one = getUserInfo(userDTO);
        if (one == null) {//从数据库查得到信息
            one = new User();
            BeanUtil.copyProperties(userDTO, one, true);//copy userDTO copy到我们的one中
            save(one);//把copy完的用户对象存储到数据库中
        } else {
            throw new ServiceException(Constants.Status_600, "用户已存在");

        }
        return one;
    }

    @Override
    public Page<User> findPage(Page<User> page, String username, String nickname, String phone, String address) {
        return userMapper.findPage(page, username, nickname, phone, address);
    }


    //封装一个方法
    private User getUserInfo(UserDTO userDTO) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", userDTO.getUsername());
        queryWrapper.eq("password", userDTO.getPassword());
        User one;
        try {
            one = getOne(queryWrapper);//从数据库查询用户信息
        } catch (Exception e) {
            LOG.error(e);
            throw new ServiceException(Constants.Status_500, "系统异常");
        }
        return one;
    }

    /**
     * 获取当前角色的菜单列表
     *
     * @param roleFlag
     * @return
     */
    private List<Menu> getRoleMenus(String roleFlag) {
        Integer roleId = roleMapper.selectByFlag(roleFlag);//当前角色的id

        //当前角色所有菜单id集合
        List<Integer> menuIds = roleMenuMapper.selectRoleId(roleId);//所有的菜单id

        //查出系统所有菜单
        List<Menu> menus = menuService.findMenus("");

        //new一个最后筛选完成之后的List
        List<Menu> roleMenus = new ArrayList<>();

        //筛选当前用户角色的菜单
        for (Menu menu : menus) {//遍历所有菜单
            if (menuIds.contains(menu.getId())) {//当前菜单包含
                roleMenus.add(menu);
            }
            List<Menu> children = menu.getChildren();//二级菜单
            boolean isSuccess = children.removeIf(child -> !menuIds.contains(child.getId()));//移除不在菜单里面的id
            if (children.size() != 0 && isSuccess) {
                roleMenus.add(menu);
            }
            //removeIf() 移除 children里面不在 menuIds集合中的 元素

        }
        return roleMenus;
    }
}
